package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class WmNewsServiceImp extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService autoScanService;

    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //校验参数
        if (dto == null){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //设置默认参数
        dto.checkParam();
        //判断用户是否为空
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //设置分页参数
        Page<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        //设置查询条件
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //根据状态
        if (dto.getStatus() != null){
            lambdaQueryWrapper.eq(WmNews::getStatus,dto.getStatus());
        }
        //根据频道
        if (dto.getChannelId() != null){
            lambdaQueryWrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        //根据关键字   标题
        if (StringUtils.isNotEmpty(dto.getKeyword())){
            lambdaQueryWrapper.eq(WmNews::getTitle,dto.getKeyword());
        }
        //根据发布时间
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null){
            lambdaQueryWrapper.between(WmNews::getPublishTime,dto.getBeginPubDate(),dto.getEndPubDate());
        }
        //查询
        page(page,lambdaQueryWrapper);
        //封装参数
        PageResponseResult responseResult = new PageResponseResult();
        responseResult.setTotal((int) page.getTotal());
        responseResult.setSize(dto.getSize());
        responseResult.setData(page.getRecords());
        responseResult.setCurrentPage(dto.getPage());
        //返回参数
        return responseResult;
    }

    @Override
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
//        校验参数
        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //判断用户是否为空
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
//        保存或者更新文章内容
        WmNews wmNews = saveOrUpdateNews(dto, user);
        // 如果是保存草稿则返回成功
        if (dto.getStatus().equals(WmNews.Status.NORMAL.getCode())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //抽取内容中所有图片
        List<String> urls = ectractUrlInfo(dto.getContent());
//        保存内容图片与素材之间的关系
        saveRelativeInfoForContent(urls,wmNews);

//        保存封面图片与素材间的关系
        saveRelativeInfoForCover(urls,wmNews,dto);

        //文章自动审核
        autoScanService.autoScanWmNews(wmNews.getId());

//        返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void saveRelativeInfo(List<String> urls, WmNews wmNews,byte type){
        if(null == urls || urls.size() == 0){
            return;
        }
        //对地址去重
        urls = urls.stream().distinct().collect(Collectors.toList());
        //通过url地址查询素材的id
        List<WmMaterial> wmMaterials = wmMaterialMapper
                .selectList(Wrappers.<WmMaterial>lambdaQuery()
                        .in(WmMaterial::getUrl, urls));
        //找到wmMaterials的id  收集
        List<Integer> ids = wmMaterials.stream().map(item -> item.getId() ).collect(Collectors.toList());
        //判断素材是否被删除过
        if (ids == null || ids.size() != urls.size()){
            throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
        }
        //批量保存文章和素材之间的关系
        wmNewsMaterialMapper.batchInsert(wmNews.getId(),ids, type);
    }

    /**
     * 保存封面图片与素材间的关系
     * @param urls
     * @param wmNews
     * @param dto
     */
    private void saveRelativeInfoForCover(List<String> urls, WmNews wmNews, WmNewsDto dto) {
        //获取传递过来的封面图片
        List<String> images = dto.getImages();
        //处理自动
        if (dto.getType() == -1){
            if (urls == null || urls.size() == 0){
                //设置为无图
                wmNews.setType((short) 0);
            }else if (urls.size() < 3){
                //设置为单图
                wmNews.setType((short) 1);
                //截取前面的1行
                images = urls.stream().limit(1).collect(Collectors.toList());
            }else {
                wmNews.setType((short) 3);
                //截取前面的3行
                images = urls.stream().limit(3).collect(Collectors.toList());
            }

            //更新文章封面的类型
            updateById(wmNews);
        }
        //判断封面是否无图
        if (images != null || images.size() > 0){
            //保存关联关系
            saveRelativeInfo(images,wmNews, (byte) 1);
        }
    }

    /**
     * 保存文章内容与素材之间的关系
     * @param urls
     * @param wmNews
     */
    private void saveRelativeInfoForContent(List<String> urls, WmNews wmNews) {
        saveRelativeInfo(urls,wmNews, (byte) 0);

    }

    /**
     * 抽取文章内容中的图片地址
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<String> urls = new ArrayList<>();
        List<Map> list = JSON.parseArray(content, Map.class);

        if (list != null && list.size() > 0 ){
            for (Map map : list) {
                if (map.get("type").equals("image")){
                    urls.add(map.get("value").toString());
                }
            }
        }
        return urls;
    }

    /**
    保存或者更新文章内容
     */
    private WmNews saveOrUpdateNews(WmNewsDto dto, WmUser wmUser) {
        WmNews wmNews = new WmNews();
        //拷贝属性
        BeanUtils.copyProperties(dto,wmNews);
        //补全图片数据   传入数组，去除“，” 转成字符串
        String images = StringUtils.join(dto.getImages().toArray(), ",");
        wmNews.setImages(images);
        //处理自动   数据库使用了unsigned  不能使用负数

        if (dto.getType() == -1){
            wmNews.setType(null);
        }

        //文章的新增
        if (dto.getId() == null){
            //保存
            save(wmNews);
        }else {
            //文章的修改
            //删除文章与素材之间的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,dto.getId()));
            //更新数据

            //更新
            updateById(wmNews);
        }
        return wmNews;
    }
}
